<template>
  <view class="container">
    <!-- 图书信息 -->
    <view class="custom-nav">
      <!-- 左上角返回按钮 -->
      <view class="nav-back" @click="navigateBack">
        <image class="back-icon" :src="'/static/icon/back.png'" mode="aspectFit" />
      </view>
      <!-- 右上角操作按钮 -->
      <view class="nav-actions1">
        <!-- 新增收藏按钮 -->
        <image class="favorite-icon" :src="isFavorited ? '/static/icon/favorite.png' : '/static/icon/unfavorite.png'"
          mode="aspectFit" @click="toggleFavorite" />
        <image class="search-icon" :src="'/static/icon/search.png'" mode="aspectFit" />
        <image class="menu-icon" :src="'/static/icon/more.png'" mode="aspectFit" />
      </view>
    </view>
    <view class="book-info">
      <image :src="book.cover" mode="aspectFill" class="book-cover" />
      <view class="info-content">
        <text class="book-title">{{ book.title }}</text>
        <text class="book-author">{{ book.author }}</text>
        <view class="book-meta">
          <text class="meta-item">{{ book.publisher }}</text>
          <text class="meta-item">{{ book.publishDate }}</text>
          <text class="meta-item">{{ book.pages }}页</text>
        </view>
        <view class="book-status" :class="book.status">
          {{ getStatusText(book.status) }}
        </view>
      </view>
    </view>

    <!-- 图书简介 -->
    <view class="section">
      <view class="section-title">图书简介</view>
      <text class="book-desc">{{ book.description }}</text>
    </view>
    <!-- 所有者简介 -->
    <view class="section">
      <view class="section-title">相关信息</view>
      <view class="borrow-info">
      <view class="info-item">
        <text class="label">所有者</text>
        <text class="value">{{ book.owner?.nickname || '未填写' }}</text> <!-- 修改此处 -->
      </view>
      <view class="info-item">
        <text class="label">联系方式</text>
        <text class="value">{{ book.ownerphone }}</text>
      </view>
      <view class="info-item">
        <text class="label">所在地址</text>
        <text class="value">{{ book.owneraddress }}</text>
      </view>
    </view>
    </view>

    <!-- 借阅信息 -->
    <view class="section" v-if="book.status === 'borrowed' || book.status === 'reserved'">
      <view class="section-title">借阅信息</view>
      <view class="borrow-info">
        <view class="info-item">
          <text class="label">借阅人</text>
          <text class="value">{{ book.currentBorrower.nickname }}</text>
        </view>
        <view class="info-item">
          <text class="label">应还时间</text>
          <text class="value">{{ book.returnDate }}</text>
        </view>
      </view>
    </view>

    <!-- 位置信息 -->
    <!-- <view class="section">
      <view class="section-title">位置信息</view>
      <view class="location-info">
        <text class="location-text">{{ book.location }}</text>
        <text class="distance">{{ book.distance }}km</text>
      </view>
    </view> -->

    <!-- 底部操作栏 -->
    <view class="action-bar">
      <button class="action-btn" :class="{ disabled: book.status !== 'available' }" @click="handleBorrow">
        {{ book.status === 'available' ? '借阅' : '已借出' }}
      </button>
      <button class="action-btn outline" @click="handleReserve" v-if="book.status === 'borrowed'">
        预约
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getBookDetail, reserveBook, checkBookIsFavorite, addFavoriteBook, removeFavoriteBook, borrowBook, updateBook } from '@/api/book';

// 图书数据
const book = ref({});
// 收藏状态
const isFavorited = ref(false);

// 页面加载时获取数据并检查收藏状态（修改后）
onMounted(async () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const bookId = currentPage.options.id;

  try {
    // 获取图书详情
    const res = await getBookDetail(bookId);
    book.value = res.data;

    // 检查是否已收藏（直接提取data字段，存储为布尔值）
    const favoriteRes = await checkBookIsFavorite(bookId);
    isFavorited.value = favoriteRes.data; // 关键修改：提取data字段
  } catch (error) {
    uni.showToast({
      title: '加载数据失败',
      icon: 'none'
    });
  }
});

// 切换收藏状态（修改后）
const toggleFavorite = async () => {
  try {
    if (isFavorited.value) { // 直接使用布尔值判断
      // 当前已收藏，调用取消收藏接口
      await removeFavoriteBook(book.value.id);
    } else {
      // 当前未收藏，调用添加收藏接口
      await addFavoriteBook(book.value.id);
    }
    // 切换状态（直接取反布尔值）
    isFavorited.value = !isFavorited.value;
    // 显示对应提示
    uni.showToast({
      title: isFavorited.value ? '收藏成功' : '取消收藏成功',
      icon: 'success'
    });
  } catch (error) {
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  }
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    available: '可借阅',
    borrowed: '已借出',
    reserved: '已预约'
  };
  return statusMap[status] || status;
};

// 借阅处理
const handleBorrow = async () => {
  if (book.value.status !== 'available') return;
  try {
    uni.showLoading({ title: '处理中' });
    // 调用借阅接口并获取后端返回的最新数据
    const response = await borrowBook(book.value.id);
    // 使用后端返回的数据更新图书状态（假设后端返回了完整的book对象）
    book.value = response.data;

    uni.showToast({
      title: '借阅成功',
      icon: 'success'
    });
  } catch (error) {
    // 错误提示已由borrowBook接口内部处理，此处无需重复提示
  } finally {
    uni.hideLoading();
  }
};

// 预约处理
const handleReserve = async () => {
  try {
    uni.showLoading({ title: '处理中' });

    await reserveBook(book.value.id);
    uni.showToast({
      title: '预约成功',
      icon: 'success'
    });
    // 更新图书状态
    book.value.status = 'reserved';
  } catch (error) {
    // 错误提示已由reserveBook接口内部处理，此处无需重复提示
  } finally {
    uni.hideLoading();
  }
};

async function getbook(bookId) {
  const res = await getBookDetail(bookId);
  book.value = res.data;
}
function navigateBack() {
  uni.navigateBack({
    delta: 1
  });
}
</script>

<style lang="scss">
.container {
  padding: 20rpx;
  padding-bottom: 120rpx;
}

.book-info {
  display: flex;
  padding: 30rpx;
  background: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;

  .book-cover {
    width: 240rpx;
    height: 340rpx;
    border-radius: 8rpx;
    margin-right: 30rpx;
  }

  .info-content {
    flex: 1;
    display: flex;
    flex-direction: column;

    .book-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 16rpx;
    }

    .book-author {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 20rpx;
    }

    .book-meta {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 20rpx;

      .meta-item {
        font-size: 24rpx;
        color: #999;
        margin-right: 20rpx;
        margin-bottom: 10rpx;
      }
    }

    .book-status {
      display: inline-block;
      padding: 6rpx 20rpx;
      border-radius: 6rpx;
      font-size: 24rpx;

      &.available {
        background: #e8f5e9;
        color: #4caf50;
      }

      &.borrowed {
        background: #fff3e0;
        color: #ff9800;
      }

      &.reserved {
        background: #e3f2fd;
        color: #2196f3;
      }
    }
  }
}

.section {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .book-desc {
    font-size: 28rpx;
    color: #666;
    line-height: 1.6;
  }

  .borrow-info {
    .info-item {
      display: flex;
      margin-bottom: 16rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        width: 140rpx;
        font-size: 28rpx;
        color: #999;
      }

      .value {
        flex: 1;
        font-size: 28rpx;
        color: #333;
      }
    }
  }

  .location-info {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .location-text {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      margin-right: 20rpx;
    }

    .distance {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.action-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  padding: 20rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .action-btn {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    font-size: 32rpx;
    color: #fff;
    background: #4caf50;
    border-radius: 40rpx;
    margin: 0 10rpx;

    &.disabled {
      background: #ccc;
    }

    &.outline {
      color: #4caf50;
      background: #fff;
      border: 2rpx solid #4caf50;
    }
  }
}

.custom-nav {
  display: flex;
  align-items: center;
  height: 100rpx;
  background-color: #ffffff;
  position: sticky;
  top: 0;
  z-index: 999;
}

/* 左上角返回按钮 */
.nav-back {
  width: 60rpx;
  /* 预留按钮点击区域 */
}

.nav-back image {
  width: 40rpx;
  /* 图片自适应 */
  height: 40rpx;
  /* 图片自适应 */
}

/* 右上角操作按钮组 */
.nav-actions1 {
  display: flex;
  margin-left: auto;
  /* 右对齐 */
  ;
  gap: 30rpx;
  /* 原有间距 */
}

.search-icon,
.menu-icon,
.favorite-icon {
  /* 新增favorite-icon样式 */
  width: 40rpx;
  /* 固定图标宽度 */
  height: 40rpx;
  /* 固定图标高度 */
}
</style>